package com.xdja.bsearch;

public class hkb {
    public static void main(String[] args) {
        int[] source = new int[]{-4, 1, 2, 2, 5, 5, 5, 8, 10};
        int index = bsearch(source, source.length - 1, 6);
        System.out.println("找到 小于等于 6的数 在第" +index+"位"+"值为:"+source[index] );
    }

    public static int bsearch(int[] arr, int n, int value) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + ((high - low) >> 1);
            if (arr[mid] > value) {
                high = mid - 1;
            } else if (arr[mid] < value) {
                low = mid + 1;
            } else if ((mid == n - 1) || (arr[mid + 1] != value)) {
                return mid;
            } else {
                low = mid + 1;
            }
        }
        if (arr[high] <= value) {
            return high;
        }
        return -1;
    }


}
